package com.cloudeye.monitor.web.controller;

import com.alibaba.fastjson.JSON;
import com.cloudeye.base.constant.Constants;
import com.cloudeye.base.constant.LogCollectionStatus;
import com.cloudeye.monitor.dto.AppInfo;
import com.cloudeye.monitor.dto.R;
import com.cloudeye.monitor.service.AppInfoService;
import com.cloudeye.monitor.service.AppStatusService;
import com.cloudeye.monitor.service.CacheService;
import com.cloudeye.monitor.web.vo.BootstrapTableVO;
import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/app")
public class AppController {

    private static final Logger LOGGER = LoggerFactory.getLogger(AppController.class);

    @Autowired
    private ZkClient zkClient;
    @Autowired
    private AppInfoService appInfoService;

    @RequestMapping("/listAppStatus.action")
    public BootstrapTableVO<AppInfo> listAppStatus() {
        Set<Map.Entry<String, Object>> hisAppEntry = CacheService.hisApp.entrySet();
        Set<Map.Entry<String, Object>> onlineAppEntry = CacheService.onlineApp.entrySet();
        List<AppInfo> rsList = new ArrayList<>();
        for (Map.Entry<String, Object> entry : onlineAppEntry) {
            rsList.add(JSON.parseObject(String.valueOf(entry.getValue()), AppInfo.class));
        }
        for (Map.Entry<String, Object> entry : hisAppEntry) {
            if (null == CacheService.onlineApp.get(entry.getKey())) {
                rsList.add(JSON.parseObject(String.valueOf(entry.getValue()), AppInfo.class));
            }
        }
        BootstrapTableVO<AppInfo> result = new BootstrapTableVO<>();
        result.setRows(rsList);
        result.setTotal(rsList.size());
        result.setPageNo(1);
        result.setTotalPage(1);
        result.setPageSize(rsList.size());
        return result;
    }

    @RequestMapping("/delHisApp")
    public R delHisApp(String app, String host) {
        String path = Constants.ROOT_PATH_PERSISTENT + Constants.SLASH + app + Constants.SLASH + host;
        LOGGER.info("删除zk节点:{}", path);
        zkClient.delete(path);
        appInfoService.delete(host, app, Constants.ZK_NODE_TYPE_PERSISTENT, LogCollectionStatus.HISTORY);
        return R.ok();
    }


    /**
     * 转换
     *
     * @param str
     * @return
     */
    private String convertStr(String str) {
        return null == str || str.contains(Constants.PLEASE_CHOOSE) ? null : str;
    }

}
